import { Button, Form, Input, message, Upload, Select } from "antd";
import { editUserUsingPost, upLoadAvatarUsingPost } from "@/api/userController";
import React, { useState, useEffect } from "react";
import {useDispatch} from "react-redux";
import {AppDispatch} from "@/stores";
import loginUser, {setLoginUser} from "@/stores/loginUser";
import { UploadOutlined } from "@ant-design/icons";
import type { UploadProps } from "antd";

interface Props {
  user: API.LoginUserVO;
}

/**
 * 用户信息编辑表单
 * @constructor
 */
const UserInfoEditForm = (props: Props) => {
  const dispatch = useDispatch<AppDispatch>();
  const [form] = Form.useForm();
  const { user } = props;
  const [isFormChanged, setIsFormChanged] = useState(false);

  // 初始化表单值
  useEffect(() => {
  form.setFieldsValue(user);
  }, [user, form]);

  // 检查表单值是否发生变化
  const checkFormChanged = () => {
    const currentValues = form.getFieldsValue();
    const initialValues = {
      phoneNumber: user.phoneNumber,
      email: user.email,
      grade: user.grade,
      workExperience: user.workExperience,
      expertiseDirection: user.expertiseDirection,
      userName: user.userName,
    };
    
    const hasChanged = Object.keys(currentValues).some(
      (key) => currentValues[key] !== initialValues[key as keyof typeof initialValues]
    );
    
    setIsFormChanged(hasChanged);
  };

  /**
   * 提交
   *
   * @param values
   */
  const doSubmit = async (values: API.UserEditRequest) => {
    const hide = message.loading("正在操作");
    try {
      await editUserUsingPost(values);
      hide();
      message.success("操作成功");
      dispatch(setLoginUser({...user, ...values}));
      setIsFormChanged(false);
    } catch (error: any) {
      hide();
      message.error("操作失败，" + error.message);
    }
  };

  /**
   * 上传头像
   */
  const handleUpload: UploadProps['customRequest'] = async (options) => {
    const { file, onSuccess, onError } = options;
    const hide = message.loading("正在上传头像");
    try {
      const res = await upLoadAvatarUsingPost({}, file as File);
      if (res.data) {
        hide();
        message.success("头像上传成功");
        dispatch(setLoginUser({...user, userAvatar: res.data}));
        onSuccess?.(res);
      }
    } catch (error: any) {
      hide();
      message.error("头像上传失败，" + error.message);
      onError?.(error);
    }
  };

  // 处理年级选择变化
  const handleGradeChange = (value: string) => {
    if (value === '已工作') {
      form.setFieldValue('workExperience', '');
    } else {
      form.setFieldValue('workExperience', '学生');
    }
    checkFormChanged();
  };

  // 处理工作经验选择变化
  const handleWorkExperienceChange = (value: string) => {
    if (value !== '学生') {
      form.setFieldValue('grade', '已工作');
    }
    checkFormChanged();
  };

  return (
    <Form
      form={form}
      style={{ marginTop: 24, maxWidth: 480 }}
      labelCol={{ span: 4 }}
      labelAlign="left"
      onFinish={doSubmit}
      onValuesChange={checkFormChanged}
    >
      <Form.Item label="头像">
        <div>
          <Upload
            customRequest={handleUpload}
            showUploadList={false}
            accept=".jpg,.jpeg,.png"
            beforeUpload={(file) => {
              const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
              if (!isJpgOrPng) {
                message.error('只能上传 JPG/PNG 格式的图片！');
                return false;
              }
              const isLt20M = file.size / 1024 / 1024 < 20;
              if (!isLt20M) {
                message.error('图片大小不能超过 20MB！');
                return false;
              }
              return true;
            }}
          >
            <Button icon={<UploadOutlined />}>修改头像</Button>
          </Upload>
          <div style={{ fontSize: '12px', color: '#999', marginTop: '4px' }}>
            仅支持20MB以下的JPG和PNG格式图片
          </div>
        </div>
      </Form.Item>
      <Form.Item 
        label="手机号" 
        name="phoneNumber"
        rules={[
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
        ]}
      >
        <Input placeholder="请输入手机号" />
      </Form.Item>
      <Form.Item 
        label="邮箱" 
        name="email"
        rules={[
          { type: 'email', message: '请输入正确的邮箱格式' }
        ]}
      >
        <Input placeholder="请输入邮箱" />
      </Form.Item>
      <Form.Item label="年级" name="grade">
        <Select
          placeholder="请选择年级"
          onChange={handleGradeChange}
          options={[
            { value: '大一', label: '大一' },
            { value: '大二', label: '大二' },
            { value: '大三', label: '大三' },
            { value: '大四', label: '大四' },
            { value: '硕士', label: '硕士' },
            { value: '已工作', label: '已工作' },
          ]}
        />
      </Form.Item>
      <Form.Item label="工作经验" name="workExperience">
        <Select
          placeholder="请选择工作经验"
          onChange={handleWorkExperienceChange}
          options={[
            { value: '学生', label: '学生' },
            { value: '一年以下', label: '一年以下' },
            { value: '一到三年', label: '一到三年' },
            { value: '三到五年', label: '三到五年' },
            { value: '五到十年', label: '五到十年' },
            { value: '十年以上', label: '十年以上' },
          ]}
        />
      </Form.Item>
      <Form.Item label="擅长方向" name="expertiseDirection">
        <Input placeholder="请输入擅长方向" />
      </Form.Item>
      <Form.Item label="用户昵称" name="userName">
        <Input placeholder="请输入您的昵称" />
      </Form.Item>
      <Form.Item>
        <Button 
          style={{ width: 180 }} 
          type="primary" 
          htmlType="submit"
          disabled={!isFormChanged}
        >
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default UserInfoEditForm;